package me.jianghs.service.impl;

import me.jianghs.client.ThriftClient;
import me.jianghs.client.ThriftClientConfig;
import me.jianghs.service.StudentService;
import me.jianghs.thrift.Student;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.async.TAsyncClientManager;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TNonblockingSocket;
import org.apache.thrift.transport.TNonblockingTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class StudentServiceImpl implements StudentService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ThriftClient thriftClient;

    @Autowired
    ThriftClientConfig thriftClientConfig;

    @Override
    public Student getStudentByName(String name) throws IOException, TException {
        TAsyncClientManager clientManager = new TAsyncClientManager();
        TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();

        TNonblockingTransport transport = new TNonblockingSocket(thriftClientConfig.getHost(), thriftClientConfig.getPort());
        me.jianghs.thrift.StudentService.AsyncClient asyncClient = new me.jianghs.thrift.StudentService.AsyncClient.Factory(clientManager, protocolFactory).getAsyncClient(transport);

        logger.info("客户端获取学生：{}的信息", name);
        asyncClient.getStudentByName(name, new AsyncMethodCallback<Student>() {
            @Override
            public void onComplete(Student student) {
                logger.info("client info:{}", student);
            }

            @Override
            public void onError(Exception e) {
                logger.error("error", e);
            }
        });
        return null;
    }

    @Override
    public void save(Student student) {
        try {
            thriftClient.open();
            logger.info("客户端请求保存对象:" + student);
            thriftClient.getService().save(student);
            logger.info("保存成功！！！");
        } catch (Exception e) {
            logger.error("客户端调用失败", e);
        } finally {
            thriftClient.close();
        }
    }
}
